"""
数据库配置和模型
"""
from sqlalchemy import create_engine, Column, Integer, String, Float, DateTime, Text, BigInteger, Date
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from datetime import datetime
from config import config

# 创建数据库引擎
engine = create_engine(
    config.DATABASE_URL,
    pool_pre_ping=True,
    pool_recycle=3600,
    echo=config.API_DEBUG
)

# 创建会话工厂
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# 创建基类
Base = declarative_base()

# 数据库依赖
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

# ==================== 数据库模型 ====================

class Stock(Base):
    """股票基本信息表"""
    __tablename__ = "stocks"
    
    id = Column(Integer, primary_key=True, index=True)
    symbol = Column(String(20), unique=True, index=True, comment="股票代码")
    name = Column(String(100), comment="股票名称")
    sector = Column(String(50), comment="所属行业")
    current_price = Column(Float, comment="当前价格")
    change = Column(Float, comment="涨跌额")
    change_percent = Column(Float, comment="涨跌幅")
    volume = Column(BigInteger, comment="成交量")
    market_cap = Column(Float, comment="市值")
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间")
    created_at = Column(DateTime, default=datetime.now, comment="创建时间")

class StockPrice(Base):
    """股票历史价格表"""
    __tablename__ = "stock_prices"
    
    id = Column(Integer, primary_key=True, index=True)
    symbol = Column(String(20), index=True, comment="股票代码")
    timestamp = Column(BigInteger, index=True, comment="时间戳")
    open = Column(Float, comment="开盘价")
    high = Column(Float, comment="最高价")
    low = Column(Float, comment="最低价")
    close = Column(Float, comment="收盘价")
    volume = Column(BigInteger, comment="成交量")
    created_at = Column(DateTime, default=datetime.now, comment="创建时间")

class TradingSignal(Base):
    """交易信号表"""
    __tablename__ = "trading_signals"
    
    id = Column(Integer, primary_key=True, index=True)
    symbol = Column(String(20), index=True, comment="股票代码")
    signal_type = Column(String(20), comment="信号类型: STRONG_BUY, BUY, HOLD, SELL, STRONG_SELL")
    strength = Column(Integer, comment="信号强度 0-100")
    price = Column(Float, comment="当前价格")
    target_price = Column(Float, nullable=True, comment="目标价格")
    stop_loss = Column(Float, nullable=True, comment="止损价格")
    reason = Column(Text, comment="推荐理由")
    indicators = Column(Text, comment="技术指标详情(JSON)")
    action_price = Column(Float, nullable=True, comment="建议操作价格")
    action_time = Column(String(50), nullable=True, comment="建议操作时间")
    signal_date = Column(Date, index=True, comment="信号日期")
    created_at = Column(DateTime, default=datetime.now, comment="创建时间")

# 创建所有表
def init_db():
    """初始化数据库"""
    Base.metadata.create_all(bind=engine)
    print("✅ 数据库表创建成功！")

if __name__ == "__main__":
    init_db()

